package com.joven.shelltest.interceptor;

import com.joven.shelltest.config.IpWhitelistProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.InetAddress;

/**
 * @author wzj
 * @since 2024/8/6 16:48
 */
@Component
@RequiredArgsConstructor
public class IpWhiteListInterceptor implements HandlerInterceptor {
    private final IpWhitelistProperties ipWhitelistProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
//        String remoteAddr = IpUtils.getClientIp(request);
        InetAddress inetAddress = InetAddress.getLocalHost();
        String remoteAddr = inetAddress.getHostAddress();
        if (ipWhitelistProperties.getAddresses().contains(remoteAddr)) {
            return true;
        } else {
            response.sendError(HttpServletResponse.SC_FORBIDDEN, "Access Denied");
            return false;
        }
    }
}
